package com.lanvideo.controller;

import com.lanvideo.entity.VideoViewRecord;
import com.lanvideo.service.VideoViewRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频观看记录控制器
 */
@RestController
@RequestMapping("/api/video-view")
public class VideoViewRecordController {

    @Autowired
    private VideoViewRecordService videoViewRecordService;

    /**
     * 记录视频观看
     */
    @PostMapping("/record")
    public ResponseEntity<Map<String, Object>> recordView(@RequestBody Map<String, Object> request, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        try {
            Integer videoId = (Integer) request.get("videoId");
            Integer watchDuration = (Integer) request.get("watchDuration");
            
            if (videoId == null) {
                result.put("success", false);
                result.put("message", "视频ID不能为空");
                return ResponseEntity.ok(result);
            }
            
            if (watchDuration == null) {
                watchDuration = 0;
            }
            
            videoViewRecordService.recordVideoView(videoId, userId, watchDuration);
            
            result.put("success", true);
            result.put("message", "观看记录已保存");
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "记录观看失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取用户的观看记录
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserViewRecords(@PathVariable Integer userId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer currentUserId = (Integer) session.getAttribute("userId");
        Integer userRole = (Integer) session.getAttribute("userRole");
        
        if (currentUserId == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 检查权限：只能查看自己的记录，或者管理员可以查看所有记录
        if (!currentUserId.equals(userId) && (userRole == null || userRole != 0)) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<VideoViewRecord> records = videoViewRecordService.getUserViewRecords(userId);
            result.put("success", true);
            result.put("records", records);
            result.put("count", records.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取观看记录失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取视频的观看记录
     */
    @GetMapping("/video/{videoId}")
    public ResponseEntity<Map<String, Object>> getVideoViewRecords(@PathVariable Integer videoId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查用户是否已登录
        Integer userRole = (Integer) session.getAttribute("userRole");
        if (userRole == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return ResponseEntity.status(401).body(result);
        }
        
        // 只有管理员和老师可以查看视频的观看记录
        if (userRole != 0 && userRole != 1) {
            result.put("success", false);
            result.put("message", "权限不足");
            return ResponseEntity.status(403).body(result);
        }
        
        try {
            List<VideoViewRecord> records = videoViewRecordService.getVideoViewRecords(videoId);
            result.put("success", true);
            result.put("records", records);
            result.put("count", records.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取观看记录失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取热门视频
     */
    @GetMapping("/popular")
    public ResponseEntity<Map<String, Object>> getPopularVideos(@RequestParam(defaultValue = "10") int limit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<VideoViewRecord> popularVideos = videoViewRecordService.getPopularVideos(limit);
            result.put("success", true);
            result.put("videos", popularVideos);
            result.put("count", popularVideos.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取热门视频失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取视频观看次数
     */
    @GetMapping("/count/{videoId}")
    public ResponseEntity<Map<String, Object>> getVideoViewCount(@PathVariable Integer videoId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Integer viewCount = videoViewRecordService.getVideoViewCount(videoId);
            result.put("success", true);
            result.put("viewCount", viewCount);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取观看次数失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
